/*
 * Restore AES encrypted backup
 *
 * License: LGPL v3
 */
package org.passwordstore.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.passwordstore.Resource;

/**
 *
 * @author thotheolh
 */
public class Restore {

    private Resource res;

    public Restore(Resource res) {
        this.res = res;
    }

    /**
     * Restore main method
     * @param bkFile
     * @return int, num of rows executed
     */
    public int doRestore(File bkFile) {
        int numRows = 0;
        ArrayList sqlContent = getFileContent(bkFile);
        //writeDebugFile(sqlContent);//Diagnostics
        //System.out.println("Sql expected Size: "+sqlContent.size());//Diagnostics
        for (int i = 0; i < sqlContent.size(); i++) {
            String str = sqlContent.get(i).toString();
            //System.out.println("Restoring: " + str);//Diagnostics
            int currRow = res.getSql().executePlainUpdate(str);
            numRows = numRows + currRow;
        }
        //System.out.println("Restored from: " + bkFile.getAbsolutePath() + "\nNum Rows: " + numRows);//Diagnostics
        return numRows;
    }

    /**
     * Read file content
     * @param file
     * @return
     */
    @SuppressWarnings({"unchecked", "unchecked", "unchecked"})
    public ArrayList getFileContent(File file) {
        ArrayList buff = null;
        StringBuffer decrypt = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            buff = new ArrayList();
            String str;
            br.readLine();
            str = br.readLine(); //Reads in the delete all statement
            buff.add(str);
            String p = String.valueOf(res.getPassword());
            byte[] passBytes = res.getAescrypt().hashpwd(p);
            while ((str = br.readLine()) != null) {
                decrypt.append(str);
//                System.out.println("Read in: "+str);
            }
            br.close();
            buff.add(res.getAescrypt().ByteToString(res.getAescrypt().decryptFile(res.getAescrypt().HexToByte(decrypt.toString()),passBytes)));
        } catch (IOException ex) {
            Logger.getLogger(Restore.class.getName()).log(Level.SEVERE, null, ex);
        }
        return buff;
    }

    /**
     * Create debug file.
     *
     * @warn Beware, do not use this to write the database content to debug file unless necessary for debugging use only
     * @param sqlContents
     */
    private void writeDebugFile(ArrayList sqlContent) {
        try {
            Writer output = null;
            String backup = "debug.sql";
            File file = new File(backup);
            output = new BufferedWriter(new FileWriter(file));
            for (int i = 0; i < sqlContent.size(); i++) {
                output.write(sqlContent.get(i).toString());
            }
            output.close();
        } catch (IOException ex) {
            Logger.getLogger(Restore.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
